//
//  BHFunApplyWriteViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/24.
//

import UIKit

class BHFunApplyWriteViewController: BHBaseViewController {
    
    var refreshDetailBlock:(() -> Void)?
    

    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-BHCompetitionApplyBottomView.viewHeight)
        view.delegate = self
        view.dataSource = self
        view.regiseterNib(nibName: "BHUserInfoWriteCell")
        view.bounces = false
        return view
    }()
    
    lazy var bottomView: BHCompetitionApplyBottomView = {
        let view = BHCompetitionApplyBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-BHCompetitionApplyBottomView.viewHeight, width: UIScreen.width, height: BHCompetitionApplyBottomView.viewHeight)
        view.delegate = self
        return view
    }()
    
    lazy var payBottomView: BHApplyPayBottomSheetView = {
        let view = BHApplyPayBottomSheetView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()
    
    fileprivate var  name: String = ""
    fileprivate var  phone: String = ""
    fileprivate var orderText: String = ""
    fileprivate var businessId: String = ""

    var funId: String = ""
    var price: String = "" {
        didSet {
            if price.isEmpty == true {
                self.payBottomView.price = "0.0"
                self.bottomView.price_label.text = "0.0"
            }else {
                self.payBottomView.price = price
                self.bottomView.price_label.text = price
            }
            
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "趣玩报名"
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomView)
        self.view.addSubview(self.payBottomView)
        
    }
    
}
extension BHFunApplyWriteViewController: BHCompetitionApplyBottomViewDelegate {
    func applyBottomDidSelectIndex(index: Int) {
        if self.name.isEmpty == true {
            BHToast.toast(text: "请输入姓名")
            return
        }
        if self.phone.isEmpty == true {
            BHToast.toast(text: "请输入手机号")
            return
        }
        if self.phone.count != 11 || !self.phone.hasPrefix("1"){
            BHToast.toast(text: "请输入正确的手机号")
            return
        }
        self.applyService()
        
    }
}
extension BHFunApplyWriteViewController: BHApplyPayBottomSheetViewDelegate {
    func goPayAct() {
        self.goAlipayAct()
    }
}

extension BHFunApplyWriteViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return 53
    }
    
}

extension BHFunApplyWriteViewController: UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHUserInfoWriteCell", for: indexPath) as! BHUserInfoWriteCell
        cell.name_label.text = indexPath.row == 0 ? "姓名":"手机号码";
        cell.infoTextFiled.placeholder = indexPath.row == 0 ? "请输入姓名":"请输入手机号码";
        if indexPath.row == 0 {
            cell.infoTextFiled.text = self.name
            cell.infoTextFiled.keyboardType = .default
        }else {
            cell.infoTextFiled.text = self.phone
            cell.infoTextFiled.keyboardType = .numberPad
        }
        cell.infoTextDidEndEditingBlock = { [weak self] text in
            if indexPath.row == 0 {
                self?.name = text
            }else {
                self?.phone = text
            }
        }
        return cell
    }
}

extension BHFunApplyWriteViewController {
    func applyService()  {
        SVProgressHUD.show()
        var dic: [String:Any] = [:]
        dic["goplayId"] = self.funId
        dic["name"] = self.name
        dic["phone"] = self.phone
        
        let manager = BHHTTPClient.init()
        manager.post(url: String.fun_detail_userApply_url, paramters: dic) { (success, errorMsg, responseDic) in
            if success == true { // 报名成功，交钱
                if self.price.isEmpty == true || self.price == "0" || self.price == "0.0" || self.price == "0.00" {
                    SVProgressHUD.dismiss()
                    BHToast.toast(text: "报名成功")
                    self.refreshDetailBlock?()
                    DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                        self.navigationController?.popViewController(animated: true)
                    }
                }else {
                    let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                    self.businessId = BHJsonTool.decodeStringFromDic(dic: result, key: "id")
                    self.createOrderService()
                }
            }else {
                SVProgressHUD.dismiss()
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    
    // 下单
    func createOrderService()  {
        BHCommonService.createOrder(type: 3, businessId: self.businessId, payType: 1) { (success, text) in
            if success == true {
                self.orderText = text
                self.payBottomView.show()
            }else {
                BHToast.toast(text: text)
            }
        }
    }
    
    // 去支付
    func goAlipayAct()  {
        BHPayManager.init().begainBuy(orderText: self.orderText) { (success, errorMsg) in
            BHToast.toast(text: errorMsg)
            if success == true {
                BHToast.toast(text: "支付成功")
                self.refreshDetailBlock?()
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}


